package com.baidumap.administrator.happystudy.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.ab.http.OnMessageResponse;
import com.ab.util.AbObjectUtil;
import com.ab.util.ProgressDialogUtils;
import com.ab.util.ScreenUtils;
import com.ab.util.ToastUtil;
import com.ab.view.swipe_menu_list_view.SwipeMenu;
import com.ab.view.swipe_menu_list_view.SwipeMenuCreator;
import com.ab.view.swipe_menu_list_view.SwipeMenuItem;
import com.ab.view.swipe_menu_list_view.SwipeMenuListView;
import com.baidumap.administrator.happystudy.R;
import com.baidumap.administrator.happystudy.ui.LoginActivity;
import com.baidumap.administrator.happystudy.api.Api;
import com.baidumap.administrator.happystudy.base.AppBaseFragment;
import com.baidumap.administrator.happystudy.base.Constant;
import com.baidumap.administrator.happystudy.model.CarList;
import com.baidumap.administrator.happystudy.model.GoodsInfo;
import com.baidumap.administrator.happystudy.model.InCart;
import com.baidumap.administrator.happystudy.utils.DBUtils;
import com.baidumap.administrator.happystudy.utils.NumberUtils;
import com.baidumap.administrator.happystudy.utils.UILUtils;
import com.socks.library.KLog;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;



/**
 * 描述：
 * 作者：xiaoxing on 17/4/12 12:04
 * 邮箱：2235445233@qq.com
 */
public class Fragment_Car extends AppBaseFragment implements OnMessageResponse {


    @Bind(R.id.layout_null)
    View layoutNull;

    @Bind(R.id.tv_edit_cart)
    TextView mTvEdit;

    @Bind(R.id.tv_price)
    TextView mTvPrice; // 合计

    @Bind(R.id.tv_total)
    TextView mTvTotal; // 总额

    @Bind(R.id.tv_count)
    TextView mTvCount; // 选中商品数

    @Bind(R.id.btn_check_all)
    CheckBox mBtnCheckAll;

    @Bind(R.id.btn_check_all_deit)
    CheckBox mBtnCheckAllEdit;

    @Bind(R.id.layout_login_cart)
    View mViewLogin;

    @Bind(R.id.layout_edit_bar)
    View layoutEditBar;

    @Bind(R.id.layout_pay_bar)
    View layoutPayBar;

    @Bind(R.id.progressBar_cart)
    ProgressBar mProgressBar;

    private CartAdapter mAdapter;
    private SwipeMenuListView mListView;
    private TextView mTvAddUp;
    private View layout;


    private ArrayList<InCart> mData = new ArrayList<InCart>();
    private HashMap<String, Boolean> inCartMap = new HashMap<String, Boolean>();// 用于存放选中的项

    private double price; // 总价
    private int num; // 选中的商品数

    private boolean isEdit; // 是否正在编辑

    private MyCartReceiver receiver;
    private boolean isLogined;


    @Override
    public void onStart() {
        super.onStart();
        registerReceiver();
    }

    @Override
    public int bindLayout() {
        return R.layout.fragment_cart;
    }

    @Override
    public void initView(View view, LayoutInflater inflater) {
        super.initView(view, inflater);
        layout = view;
        setOnListener();
        initListView();
        initData();
    }

    @Override
    public void doBusiness(Context mContext) {
        super.doBusiness(mContext);
        isLogined = sHelper.getBoolean(Constant.IS_LOGIN);

        if (isLogined) {
            mViewLogin.setVisibility(View.GONE);
        } else {
            mViewLogin.setVisibility(View.VISIBLE);
        }
        if (isLogined) {
            KLog.e("== ======>>>获取web段购物车数据===>>getWebCartList");
            Api.carList(this, sHelper.getString(Constant.TOKEN), sHelper.getString(Constant.UID));
        }
    }

    private void setOnListener() {

        mBtnCheckAll.setOnCheckedChangeListener(checkAllListener);
        mBtnCheckAllEdit.setOnCheckedChangeListener(checkAllListener);
    }


    @OnClick({R.id.btn_login_cart, R.id.btn_collect, R.id.btn_delete, R.id.btn_pay, R.id.btn_more, R.id.tv_edit_cart, R.id.layout_edit_bar, R.id.layout_pay_bar})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_login_cart: // 登录
                gotoLogin();
                break;
            case R.id.btn_collect: // 移入关注
                add2Collect();
                break;
            case R.id.btn_delete: // 删除
                ProgressDialogUtils.showProgressDialog(getActivity(), "数据删除中...");
                deleteInCart();
                break;
            case R.id.tv_edit_cart: // 编辑
                editInCart();
                break;
            case R.id.btn_pay: // 结算
                pay();
                break;
            case R.id.btn_more: // 去秒杀
                ToastUtil.showMessage(getActivity(), "去秒杀");
//                Bundle bundle = new Bundle();
//                bundle.putString("tabSelected", "shouye");
//                Intent intent = new Intent(getActivity(), Activity_Main.class);
//                startActivity(intent, bundle);
                break;

            default:
                break;
        }
    }


    @Override
    public void initData() {
        super.initData();
        // 异步从数据库中获取数据
        //new InCartTask().execute();
        if (isLogined) {
            KLog.e("== ======>>>获取web段购物车数据===>>getWebCartList");
            Api.carList(this, sHelper.getString(Constant.TOKEN), sHelper.getString(Constant.UID));
        }
    }

    /**
     * 选中商品改变
     */
    private void notifyCheckedChanged() {
        price = 0;
        num = 0;
        for (int i = 0; i < mData.size(); i++) {
            Boolean isChecked = inCartMap.get(mData.get(i).getGoodsId());
            if (isChecked != null && isChecked) {
                InCart inCart = mData.get(i);
                num += inCart.getNum();
                price += inCart.getGoodsPrice() * inCart.getNum();
            }
        }
        mTvPrice.setText(NumberUtils.formatPrice(price));
        mTvTotal.setText("总额：" + NumberUtils.formatPrice(price));
        mTvCount.setText("(" + num + ")");
        mTvAddUp.setText("小计：" + NumberUtils.formatPrice(price));

    }

    /**
     * 通知更新购物车商品数量
     */
    private void notifyInCartNumChanged() {
        // 通知主页刷新购物车商品数
        Intent intent = new Intent();
        intent.setAction(Constant.BROADCAST_FILTER.FILTER_CODE);
        intent.putExtra(Constant.BROADCAST_FILTER.EXTRA_CODE,
                Constant.INTENT_KEY.REFRESH_INCART);
        getActivity().sendBroadcast(intent);
    }

    private void initListView() {
        mListView = (SwipeMenuListView) layout.findViewById(R.id.listView_cart);
        View foot = getActivity().getLayoutInflater().inflate(
                R.layout.foot_cart_list, null);
        mTvAddUp = (TextView) foot.findViewById(R.id.tv_add_up);
        mListView.addFooterView(foot, null, false);
        mAdapter = new CartAdapter();
        mListView.setAdapter(mAdapter);
        // step 1. create a MenuCreator
        SwipeMenuCreator creator = new SwipeMenuCreator() {

            @Override
            public void create(SwipeMenu menu) {
                // create "open" item
                SwipeMenuItem deleteItem = new SwipeMenuItem(getActivity());
                // set item background
                deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9,
                        0x3F, 0x25)));
                // set item width
                deleteItem
                        .setWidth(ScreenUtils.getScreenWidth(getActivity()) / 3);
                // set item title
                deleteItem.setTitle("删除");
                // set item title fontsize
                deleteItem.setTitleSize(18);
                // set item title font color
                deleteItem.setTitleColor(Color.WHITE);
                // add to menu
                menu.addMenuItem(deleteItem);

            }
        };
        // set creator
        mListView.setMenuCreator(creator);

        // step 2. listener item click event
        mListView.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public void onMenuItemClick(int position, SwipeMenu menu, int index) {
                // index是menu的菜单序号
                deleteItem(position);
            }
        });
        mListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
//                InCart inCart = mData.get(position);
//                GoodsInfo info = new GoodsInfo(inCart.getGoodsId(), inCart
//                        .getGoodsName(), inCart.getGoodsIcon(), inCart
//                        .getGoodsType(), inCart.getGoodsPrice(), inCart
//                        .getGoodsPercent(), inCart.getGoodsComment(), inCart
//                        .getIsPhone(), inCart.getIsFavor(), inCart.getRec_id());
//                Intent intent = new Intent(getActivity(), Activity_Detali.class);
//                intent.putExtra(Constant.INTENT_KEY.INFO_TO_DETAIL, info);
//                startActivityForResult(intent,
//                        Constant.INTENT_KEY.REQUEST_CART_TO_DETAIL);
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        // 将layout从父组件中移除
        ViewGroup parent = (ViewGroup) layout.getParent();
        parent.removeView(layout);
    }

    /**
     * 获取数字
     *
     * @param tvNum
     * @return
     */
    private int getNum(TextView tvNum) {
        String num = tvNum.getText().toString().trim();
        return Integer.valueOf(num);

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constant.INTENT_KEY.LOGIN_REQUEST_CODE) {
            if (resultCode == Constant.INTENT_KEY.LOGIN_RESULT_SUCCESS_CODE) {

                int type = sHelper.getInt("login_type", 0);
                String uid = "";
                String icon = "";
                switch (type) {
                    case 1:
                        uid = data.getStringExtra("uid");
                        break;
                    case 2:
                        uid = data.getStringExtra("screen_name");
                        icon = data.getStringExtra("profile_image_url");
                        break;

                    default:
                        break;
                }
                mViewLogin.setVisibility(View.GONE);
//                Activity_Main activity = (Activity_Main) getActivity();
//                // 将登录结果设置给MainActivity
//                activity.setIsLogined(true, uid);
            }
        } else if (requestCode == Constant.INTENT_KEY.REQUEST_CART_TO_DETAIL) {
            // 刷新购物车
            initData();
            // 刷新价格
            notifyCheckedChanged();
        }
    }

    class CartAdapter extends BaseAdapter {

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View inflate = null;
            ViewHolder holder = null;
            if (convertView == null) {
                // 复用乱序问题
                inflate = getActivity().getLayoutInflater().inflate(
                        R.layout.item_fragment_cart_list, null);
                holder = new ViewHolder();
                holder.btnCheck = (CheckBox) inflate
                        .findViewById(R.id.btn_check);
                holder.btnReduce = (Button) inflate
                        .findViewById(R.id.btn_cart_reduce);
                holder.btnAdd = (Button) inflate
                        .findViewById(R.id.btn_cart_add);
                holder.btnNumEdit = (Button) inflate
                        .findViewById(R.id.btn_cart_num_edit);
                holder.imgGoods = (ImageView) inflate
                        .findViewById(R.id.img_goods);
                holder.tvGoodsName = (TextView) inflate
                        .findViewById(R.id.tv_goods_name);
                holder.tvGoodsPrice = (TextView) inflate
                        .findViewById(R.id.tv_goods_price);
                inflate.setTag(holder);
            } else {
                inflate = convertView;
                holder = (ViewHolder) inflate.getTag();
            }
            final InCart inCart = mData.get(position);
            holder.tvGoodsName.setText(inCart.getGoodsName());
            holder.tvGoodsPrice.setText(NumberUtils.formatPrice(inCart
                    .getGoodsPrice()));
            holder.btnNumEdit.setText("" + inCart.getNum());

            UILUtils.displayImage(getActivity(), inCart.getGoodsIcon(),
                    holder.imgGoods);

            if (inCart.getNum() > 1) {
                holder.btnReduce.setEnabled(true);
            } else {
                holder.btnReduce.setEnabled(false);
            }
            // 避免由于复用触发onChecked()事件
            holder.btnCheck.setOnCheckedChangeListener(null);
            Boolean isChecked = inCartMap.get(inCart.getGoodsId());
            if (isChecked != null && isChecked) {
                holder.btnCheck.setChecked(true);
            } else {
                holder.btnCheck.setChecked(false);
            }
            final ViewHolder holder2 = holder;
            holder.btnReduce.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    int num = getNum(holder2.btnNumEdit);
                    num--;
                    inCart.setNum(num);
                    inCart.save();
                    notifyInCartNumChanged();
                    // 如果被选中，更新价格
                    if (holder2.btnCheck.isChecked()) {
                        notifyCheckedChanged();
                    }
                    Log.e("onClick", "holder2.btnCheck.isChecked() = "
                            + holder2.btnCheck.isChecked());
                    holder2.btnNumEdit.setText("" + num);
                    if (num == 1) {
                        holder2.btnReduce.setEnabled(false);
                    }
                }
            });
            holder.btnAdd.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    holder2.btnReduce.setEnabled(true);
                    int num = getNum(holder2.btnNumEdit);
                    num++;
                    inCart.setNum(num);
                    inCart.save();
                    notifyInCartNumChanged();
                    // 如果被选中，更新价格
                    if (holder2.btnCheck.isChecked()) {
                        notifyCheckedChanged();
                    }
                    Log.e("onClick", "holder2.btnCheck.isChecked() = "
                            + holder2.btnCheck.isChecked());
                    holder2.btnNumEdit.setText("" + num);
                }
            });
            holder.btnCheck
                    .setOnCheckedChangeListener(new OnCheckedChangeListener() {

                        @Override
                        public void onCheckedChanged(CompoundButton buttonView,
                                                     boolean isChecked) {
                            if (isChecked) {
                                inCartMap.put(inCart.getGoodsId(), isChecked);
                                // 如果所有项都被选中，则点亮全选按钮
                                if (inCartMap.size() == mData.size()) {
                                    mBtnCheckAll.setChecked(true);
                                    mBtnCheckAllEdit.setChecked(true);
                                }
                            } else {
                                // 如果之前是全选状态，则取消全选状态
                                if (inCartMap.size() == mData.size()) {
                                    mBtnCheckAll
                                            .setOnCheckedChangeListener(null);
                                    mBtnCheckAllEdit
                                            .setOnCheckedChangeListener(null);
                                    mBtnCheckAll.setChecked(false);
                                    mBtnCheckAllEdit.setChecked(false);
                                    mBtnCheckAll
                                            .setOnCheckedChangeListener(checkAllListener);
                                    mBtnCheckAllEdit
                                            .setOnCheckedChangeListener(checkAllListener);
                                }
                                inCartMap.remove(inCart.getGoodsId());
                            }
                            notifyCheckedChanged();
                        }
                    });
            return inflate;
        }

        @Override
        public int getCount() {
            // 若mData.size() == 0，显示layoutNull
            if (mData.size() == 0) {
                mListView.setVisibility(View.GONE);
                mTvEdit.setVisibility(View.GONE);
                layoutEditBar.setVisibility(View.GONE);
                layoutPayBar.setVisibility(View.GONE);
                layoutNull.setVisibility(View.VISIBLE);
                isEdit = false;
            } else {
                mListView.setVisibility(View.VISIBLE);
                mTvEdit.setVisibility(View.VISIBLE);
                layoutNull.setVisibility(View.GONE);
                if (isEdit) {
                    layoutEditBar.setVisibility(View.VISIBLE);
                } else {
                    layoutPayBar.setVisibility(View.VISIBLE);
                }
            }
            return mData.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

    }

    class ViewHolder {
        CheckBox btnCheck;
        Button btnAdd;
        Button btnReduce;
        Button btnNumEdit;
        ImageView imgGoods;
        TextView tvGoodsName;
        TextView tvGoodsPrice;
    }

    class InCartTask extends AsyncTask<Void, Void, List<InCart>> {

        @Override
        protected List<InCart> doInBackground(Void... params) {
            return DBUtils.getInCart();
        }

        @Override
        protected void onPostExecute(List<InCart> result) {
            super.onPostExecute(result);
            mData.clear();
            mData.addAll(result);

            if (mBtnCheckAll.isChecked()) {
                checkAll();
            }
            mAdapter.notifyDataSetChanged();
            notifyCheckedChanged();
            if (mData.size() == 0) {
                mListView.setVisibility(View.GONE);
            } else {
                mListView.setVisibility(View.VISIBLE);
            }
        }

    }


    /**
     * 结算
     */
    private void pay() {
        if (num == 0) {
            ToastUtil.showMessage(getActivity(), "您还没有选择商品哦");

        } else {
            ToastUtil.showMessage(getActivity(), "恭喜，付款成功");
        }
    }

    /**
     * 全选，将数据加入inCartMap
     */
    private void checkAll() {
        for (int i = 0; i < mData.size(); i++) {
            inCartMap.put(mData.get(i).getGoodsId(), true);
        }
    }

    /**
     * 删除列表项
     */
    private void deleteItem(int position) {
        InCart inCart = mData.get(position);
        DBUtils.deleteCart(inCart);
        inCartMap.remove(inCart.getGoodsId());
        mData.remove(position);
        notifyCheckedChanged();
        notifyInCartNumChanged();
        mAdapter.notifyDataSetChanged();

    }

    /**
     * 编辑
     */
    private void editInCart() {
        isEdit = !isEdit;
        if (isEdit) {
            mTvEdit.setText("完成");
            layoutPayBar.setVisibility(View.GONE);
            layoutEditBar.setVisibility(View.VISIBLE);
        } else {
            mTvEdit.setText("编辑");
            layoutPayBar.setVisibility(View.VISIBLE);
            layoutEditBar.setVisibility(View.GONE);
        }
    }

    /**
     * 删除选中项
     */
    private void deleteInCart() {
        // TODO Auto-generated method stub
        if (inCartMap.size() == 0) {
            ToastUtil.showMessage(getActivity(), "您还没有选择商品哦");
            return;
        }
        for (int i = 0; i < mData.size(); i++) {
            Boolean isChecked = inCartMap.get(mData.get(i).getGoodsId());
            if (isChecked != null && isChecked) {
                InCart inCart = mData.get(i);
                KLog.e("rec_id======" + inCart.getRec_id());
                //TODO 删除商品接口添加处
               // Api.dropGoods(this, sHelper.getString(Constant.UID), sHelper.getString(Constant.TOKEN), inCart.getRec_id() + "");
                DBUtils.deleteCart(inCart);
            }
        }
        inCartMap.clear();
        mBtnCheckAll.setChecked(false);
        mBtnCheckAllEdit.setChecked(false);
        notifyCheckedChanged();
        notifyInCartNumChanged();
        initData();
    }

    /**
     * 移入关注
     */
    private void add2Collect() {
        if (inCartMap.size() == 0) {
            ToastUtil.showMessage(getActivity(), "您还没有选择商品哦");
            return;
        }
        for (int i = 0; i < mData.size(); i++) {
            Boolean isChecked = inCartMap.get(mData.get(i).getGoodsId());
            if (isChecked != null && isChecked) {
                InCart inCart = mData.get(i);
                GoodsInfo goodsInfo = new GoodsInfo(inCart.getGoodsId(),
                        inCart.getGoodsName(), inCart.getGoodsIcon(),
                        inCart.getGoodsType(), inCart.getGoodsPrice(),
                        inCart.getGoodsPercent(), inCart.getGoodsComment(),
                        inCart.getIsPhone(), 1, 0);
                //TODO 收藏接口添加处
//                Api.collect(this, AppBaseApplication.getSingleton().getM_userInfo().getContent().getUser_id(), goodsInfo.getGoodsId());

                // 如果没有收藏过，则加入收藏
                if (!DBUtils.hasFavor(goodsInfo)) {
                    goodsInfo.save();
                }
            }
        }
        ToastUtil.showMessage(getActivity(), "关注成功");
    }

    /**
     * 跳转到登录界面
     */
    private void gotoLogin() {
        Intent intent = new Intent(getActivity(), LoginActivity.class);
        startActivityForResult(intent, Constant.INTENT_KEY.LOGIN_REQUEST_CODE);
    }

    private OnCheckedChangeListener checkAllListener = new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView,
                                     boolean isChecked) {
            mBtnCheckAll.setChecked(isChecked);
            mBtnCheckAllEdit.setChecked(isChecked);
            if (isChecked) {
                checkAll();
            } else {
                inCartMap.clear();
            }
            notifyCheckedChanged();
            mAdapter.notifyDataSetChanged();
        }

    };

    /**
     * 注册广播接收者
     */
    private void registerReceiver() {
        if (AbObjectUtil.isNull(receiver)) {
            receiver = new MyCartReceiver();
            IntentFilter filter = new IntentFilter(
                    Constant.BROADCAST_FILTER.FILTER_CODE);
            getActivity().registerReceiver(receiver, filter);

        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(receiver);
    }

    @Override
    public void onMessageResponse(String url, JSONObject jo) throws JSONException {

        mProgressBar.setVisibility(View.GONE);
        if (url.equals(Constant.CART_LIST) && jo != null) {
            KLog.e("购物车列表数据==" + jo.toString());
            CarList carList = new CarList(jo.toString());
            mData.clear();
            if (carList.getCode().equals("200")) {
                List<CarList.DataBean.GoodsDataBean> contentBeanList = carList.getData().getGoods_data();
                if (contentBeanList.size() > 0) {
                    List<InCart> inCartList = new ArrayList<>();
                    for (int i = 0; i < contentBeanList.size(); i++) {

//                        final InCart mInCart = new InCart(contentBeanList.get(i).getProduct_id() + "",
//                                contentBeanList.get(i).getProduct_name(), "",
//                                "", Double.parseDouble(contentBeanList.get(i).getPrice()),
//                                "", 0,
//                                0, 0, Integer.parseInt(contentBeanList.get(i).getGoods_num()), Integer.parseInt(contentBeanList.get(i).getCart_id()));
//                        inCartList.add(mInCart);

                    }

                    mData.addAll(inCartList);

                    if (mBtnCheckAll.isChecked()) {
                        checkAll();
                    }
                    mAdapter.notifyDataSetChanged();
                    notifyCheckedChanged();
                    if (mData.size() == 0) {
                        mListView.setVisibility(View.GONE);
                    } else {
                        mListView.setVisibility(View.VISIBLE);
                    }
                } else {
                    mAdapter.notifyDataSetChanged();
                    notifyCheckedChanged();
                    if (mData.size() == 0) {
                        mListView.setVisibility(View.GONE);
                    } else {
                        mListView.setVisibility(View.VISIBLE);
                    }
                }

            }
        }

    }


    @Override
    public void onMessageResponse(String url, JSONArray jo) throws JSONException {

    }

    @Override
    public void onMessageResponse(String url, String str) throws Exception {

    }

    class MyCartReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String extra = intent
                    .getStringExtra(Constant.BROADCAST_FILTER.EXTRA_CODE);
            if (extra.equals(Constant.INTENT_KEY.REFRESH_INCART)) {
                initData();
            }
        }

    }


}